import React, {useCallback, useEffect, useRef, useState} from "react";
import {UniversityModel} from "@/common/apis/model";
import LocalData from "@/common/local_data";
import {
  majorsListApi,
  universityListApi
} from "@/common/apis/home_datasource";

import LogUtils from "@/utils/log";
import Taro, {usePullDownRefresh, useReachBottom} from "@tarojs/taro";
import Utils from "@/utils/common";

import {View} from "@tarojs/components";

import {ActionSheet, Cell, Empty, Search, Sticky, Tab, Tabs} from "@antmjs/vantui";
import EventUtils from "@/utils/event_utils";
import DynamicForm, {FormConfig} from "@/components/DynamicForm";


definePageConfig({
  navigationBarTitleText: '选择学校/输入组织',
  onReachBottomDistance: 50,
})


export default function CompanyOrUniversity() {
  const tabs = useRef([
    {
      title: "选择学校",
      key: 0 // Key is the actual enum value (10)
    },
    {
      title: "输入组织",
      key: 1 // Key is the actual enum value (10)
    },

  ]);

  return (
    <View className='container'>
      <Tabs
        sticky
        color='#56abe4'
      >
        {
          tabs.current.map((item, index) => (
            <Tab key={`tabs#demo1${item.key}`} title={item.title}>
              <View>
                {item.key == 1 ? <InputCompany item={item}></InputCompany> :
                  <UniversityList item={item}></UniversityList>}
              </View>
            </Tab>
          ))
        }
      </Tabs>
    </View>
  )
}


function UniversityList() {
  const [items, setItems] = useState<UniversityModel[]>()
  const isFetching = useRef(false);
  const pageIndex = useRef(LocalData.startPage);
  const hasMore = useRef(true);
  const inputKey = useRef('');
  const selectItem = useRef<UniversityModel | null>(null);
  const [majors, setMajors] = useState(false)
  const majorsList = useRef<UniversityModel[]>([])
  const fetchData = useCallback((isRefresh) => {
    if (isFetching.current) {
      return;
    }
    isFetching.current = true;
    if (isRefresh) {
      pageIndex.current = LocalData.startPage;
    }
    let newHasMore: boolean = true;
    universityListApi(inputKey.current, isRefresh, pageIndex.current).then((res2) => {
      if (res2) {
        newHasMore = res2.length >= LocalData.limit;
        if (isRefresh || pageIndex.current === LocalData.startPage) {
          setItems(res2)
          Taro.pageScrollTo({
            scrollTop: 0,
            duration: 300
          }).then(r => {

          });
        } else {
          setItems(prevItems => [...prevItems, ...res2]);
        }
      } else {
        newHasMore = false;
      }
      hasMore.current = newHasMore;
      isFetching.current = false;
    })
  }, [setItems]);

  useEffect(() => {
    channelEmit.current = Utils.getChannel(Utils.getI())
    setItems(undefined);
    fetchData(true)
    return () => {
    }
  }, [fetchData]);
  usePullDownRefresh(() => {
    fetchData(true)
  })
  useReachBottom(() => {
    if (!hasMore.current || isFetching.current) {
      return;
    }
    pageIndex.current++
    fetchData(false)
    LogUtils.info('bottom')
  })


  const searchAction = useCallback((e) => {
    if (!Utils.isNotBlank(e.detail)) {
      Utils.showErrorToast('请输入学校名称')
      return;
    }
    if (e.detail === inputKey.current) {
      return;
    }
    inputKey.current = e.detail;
    fetchData(true)
  }, [fetchData]);


  const channelEmit = useRef<Taro.EventChannel | null>();
  const handleMajorsSelect = (e: any) => {
    //如果项目id一样就不更新
    //拼接字符串
    if (selectItem.current) {
      LogUtils.info(`${selectItem.current?.schoolName}${e.detail}`)
      Utils.emit(channelEmit.current, EventUtils.OK, `${selectItem.current?.schoolName}/${e.detail.name}`)
      Utils.navigateBack()
    }
  }


  const getList2 = useCallback(() => {
    const sN = selectItem.current?.schoolName
    if (sN) {
      majorsListApi(sN).then((res) => {
        if (res) {
          //便利res 把codeName复制到name上面
          for (let i = 0; i < res.length; i++) {
            res[i].name = res[i].codeName
          }
          majorsList.current = res
          setMajors(true)
        }
      })
    }

  }, []);


  return (
    <View style={{backgroundColor: 'white'}}>
      <View>
        <Sticky offsetTop='50'>
          <Search
            placeholder='请输入学校名称'
            onSearch={searchAction}
          />
        </Sticky>
        <View style={{height: "100vh", paddingTop: "0px", boxSizing: 'border-box'}}>
          {
            items && !Utils.isEmpty(items) ? <View>
              {
                items.map((item, index) => {

                  return <View key={index}>
                    <Cell
                      isLink
                      title={item.schoolName} onClick={() => {
                      selectItem.current = item
                      getList2()
                    }}
                    />
                  </View>
                })
              }
            </View> : <Empty description='暂无数据' />
          }
        </View>
        <ActionSheet
          show={majors}
          actions={majorsList.current}
          onClose={() => setMajors(false)}
          onSelect={(e) => handleMajorsSelect(e)}
          lockScroll
        />
      </View>
    </View>
  )
}


function InputCompany() {
  const inputCompanyConfigs: FormConfig[] = [
    {
      type: 'input',
      name: 'company', // Logical name for recipient name
      label: '组织',       // Label text (without *)
      placeholder: '请输入组织',
      layout: 'horizontal',
      required: true,
      rules: []
    },
  ];


  const eventChannel = useRef<Taro.EventChannel | null>();


  useEffect(() => {
    const instance = Utils.getI();
    eventChannel.current = Utils.getChannel(instance);
  }, []);


  // 提交回调
  const handleSubmit = (values) => {
    Utils.emit(eventChannel.current, EventUtils.OK, values.company)
    Utils.navigateBack()
  };

  // 错误回调
  const handleError = (errors) => {
    console.error('Form errors:', errors);
  };

  return (
    <View>
      <DynamicForm
        marginTop={50}
        formConfigs={inputCompanyConfigs}
        onSubmit={handleSubmit}
        onError={handleError}
        submitText='确认'
      />
    </View>
  );
}
